package dapps.web;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.jasig.cas.client.authentication.AttributePrincipal;
import org.jasig.cas.client.validation.AssertionImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.Authentication;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
import org.springframework.security.ui.WebAuthenticationDetails;
import org.springframework.security.ui.webapp.AuthenticationProcessingFilter;

import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class MainAction extends ActionSupport {

	@Autowired
	private org.springframework.security.AuthenticationManager authenticationManager;

	@Override
	public String execute() throws Exception {
		String username = "";
		String password = "123";
		HttpServletRequest request = ServletActionContext.getRequest();
		AssertionImpl assertion = (AssertionImpl) request.getSession().getAttribute("_const_cas_assertion_");
		AttributePrincipal ap = assertion.getPrincipal();
		username = ap.getName();
		if (request.getSession().getAttribute(AuthenticationProcessingFilter.SPRING_SECURITY_LAST_USERNAME_KEY)==null) {
			login(username,password);
			System.out.println("登录"+username);
		}else{
			if(!username.equals((String)request.getSession().getAttribute(AuthenticationProcessingFilter.SPRING_SECURITY_LAST_USERNAME_KEY))){
				request.getSession().invalidate();
				System.out.println("重登录"+username+"替换"+(String)request.getSession().getAttribute(AuthenticationProcessingFilter.SPRING_SECURITY_LAST_USERNAME_KEY));
				login(username,password);
				
			}
		}
		return SUCCESS;

	}
	private void login(String username, String password) throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		UsernamePasswordAuthenticationToken authen = new UsernamePasswordAuthenticationToken(username, password);
		// 保存用户名到 session里
		request.getSession().setAttribute(
						AuthenticationProcessingFilter.SPRING_SECURITY_LAST_USERNAME_KEY,
						username);
		WebAuthenticationDetails webdetails = new WebAuthenticationDetails(request);
		// 注意:这里 setDetails的对象一定要是WebAuthenticationDetails
		authen.setDetails(webdetails);		// 这里验证不通过会返回null对象
		Authentication auth1 = authenticationManager.authenticate(authen);
		SecurityContextHolder.getContext().setAuthentication(auth1);
		System.out.println("认证是否通过: " + auth1.isAuthenticated()+".request:"+request.getRequestURI());
	}

	public org.springframework.security.AuthenticationManager getAuthenticationManager() {
		return authenticationManager;
	}

	public void setAuthenticationManager(
			org.springframework.security.AuthenticationManager authenticationManager) {
		this.authenticationManager = authenticationManager;
	}

}
